#include "widget.h"
#include "ui_widget.h"
#include "QRandomGenerator"

QStringList iconStringList = {
    ":/icon/apple.png",
    ":/icon/banana.png",
    ":/icon/orange.png",
    ":/icon/pear.png",
    ":/icon/watermelon.png"
};

Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);

    mBtnGroup = new QButtonGroup();
    mBtnGroup->addButton(ui->rbListMode, 0);
    mBtnGroup->addButton(ui->rbIconMode, 1);

    ui->rbListMode->setChecked(true);
    ui->lwProvince->setViewMode(QListView::ListMode);

    connect(ui->rbIconMode, &QRadioButton::clicked, this, &Widget::onRadioButtonClicked);
    connect(ui->rbListMode, &QRadioButton::clicked, this, &Widget::onRadioButtonClicked);

    connect(ui->lwProvince, &QListWidget::itemClicked, this, &Widget::onItemClicked);
    connect(ui->lwProvince, &QListWidget::itemDoubleClicked, this, &Widget::onItemDoubleClicked);

    connect(ui->btnAdd, &QPushButton::clicked, this, &Widget::onBtnAddClicked);
    connect(ui->btnInsert, &QPushButton::clicked, this, &Widget::onBtnInsertClicked);
    connect(ui->btnDelete, &QPushButton::clicked, this, &Widget::onBtnDeleteClicked);
}

Widget::~Widget()
{
    delete ui;
}

/** RadioButton的点击事件
 * @brief Widget::onRadioButtonClicked
 */
void Widget::onRadioButtonClicked()
{
    int checkId = mBtnGroup->checkedId();
    if(checkId == 0) {
        // 列表模式
        ui->lwProvince->setViewMode(QListView::ListMode);
    } else if (checkId == 1) {
        // icon模式
        ui->lwProvince->setViewMode(QListView::IconMode);
    }
}

/** item的单击
 * @brief Widget::onItemClicked
 * @param item
 */
void Widget::onItemClicked(QListWidgetItem *item)
{
    ui->leCurrentItem->setText(item->text());
}

/** item的双击
 * @brief Widget::onItemDoubleClicked
 * @param item
 */
void Widget::onItemDoubleClicked(QListWidgetItem *item)
{
    item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable);
}

/** 添加
 * @brief Widget::onBtnAddClicked
 */
void Widget::onBtnAddClicked()
{
    int iconIndex = QRandomGenerator::global()->generate()%5;

    QIcon icon(iconStringList[iconIndex]);
    QString text = ui->leInput->text();

    QListWidgetItem* item = new QListWidgetItem(icon, text);
    ui->lwProvince->addItem(item);
}

/** 插入
 * @brief Widget::onBtnInsertClicked
 */
void Widget::onBtnInsertClicked()
{
    int iconIndex = QRandomGenerator::global()->generate()%5;

    QIcon icon(iconStringList[iconIndex]);
    QString text = ui->leInput->text();

    QListWidgetItem* item = new QListWidgetItem(icon, text);

    int currentRow = ui->lwProvince->currentRow();
    ui->lwProvince->insertItem(currentRow, item);
}

/** 删除
 * @brief Widget::onBtnDeleteClicked
 */
void Widget::onBtnDeleteClicked()
{
    QListWidgetItem* item = ui->lwProvince->currentItem();
    ui->lwProvince->removeItemWidget(item);
    delete item;
}
